<template>
  <div class="page">
    <div class="page-prev" v-show="index !== 1" @click="prev()">上</div>
    <div class="page-content">
      <div
        class="page-item"
        :class="{ active: index == item }"
        v-for="item in list"
        :key="item"
        @click="change(item)"
      >
        {{ item }}
      </div>
    </div>
    <div class="page-next" @click="next()" v-show="index != maxPage">
      {{ props.next?props.next:"下一页" }}
    </div>
  </div>
</template>
<script setup>
import { ref, watch } from 'vue'
let props = defineProps(['total',"next"])
let $emits = defineEmits(['changeIndex'])

let index = ref(1) //当前选中的页码
let list = ref([1, 2, 3, 4, 5]) //显示的页码

let createPage = () => {
  let shownum = ref(10) //每页显示10条数据
  let showpage = ref(5) //连续出现的页码数

  let middleNum = Math.ceil(showpage.value / 2) //3
  let maxPage = ref(Math.ceil(props.total / shownum.value))

  //向上取整
  let start = 1 //开始
  let end = maxPage.value > showpage.value ? showpage.value : maxPage.value
  //结尾控制

  if (index.value > middleNum) {
    //到了中间
    start = index.value - middleNum + 1 //开始
    end = index.value + middleNum - 1 //结尾
  }
  if (index.value > maxPage.value - middleNum + 1) {
    //到了末尾
    start = maxPage.value - showpage.value + 1
    end = maxPage.value
  }
  start = start > 1 ? start : 1 //开头控制

  list.value = [] //清空
  for (let i = start; i <= end; i++) {
    list.value.push(i)
  }
  $emits("changeIndex",index.value);
}

let prev = () => {
  index.value--
  createPage()
}
let next = () => {
  index.value++
  createPage()
}

let change = (item) => {
  index.value = item
  createPage()
}
watch(
  () => props.total,
  () => {
    index.value = 1
    createPage()
  },
  {
    immediate: true
  }
)
</script>

<style scoped>
.page {
  width: 600px;
}
.page div {
  float: left;
}
.page .page-prev,
.page .page-next {
  width: 40px;
  height: 40px;
  background-color: #409eff;
  color: #000000;
  line-height: 40px;
  text-align: center;
  margin-left: 10px;
}
.page .page-item {
  width: 40px;
  height: 40px;
  background-color: #409eff;
  color: #000000;
  line-height: 40px;
  text-align: center;
  margin-left: 10px;
}
.page .active {
  color: aliceblue !important;
}
</style>
